package com.example.administrator.social.activitys;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.social.R;
import com.example.administrator.social.adapter.CharRecyclerAdapter;
import com.example.administrator.social.model.CharText;
import com.example.administrator.social.model.Contact;
import com.example.administrator.social.model.User;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.example.administrator.social.view.CircleImageView;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class CharActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener,
    TextView.OnEditorActionListener {
    public static  final int MESSAGE_SEND_ERROR = -1;
    public static  final int MESSAGE_SEND_PROGRESS = 0;
    public static  final int MESSAGE_SEND_SUCCESS = 1;
    TextView mGoBackButton;
    RecyclerView mCharRecyclerView;
    CharRecyclerAdapter mCharAdapter;
    Context mContext;
    String mCharWithUser;
    //bottom input Layout
    EditText mEditSendText;
    CircleImageView mShowVoiceButton,mAddExpressionButton,mAddOtherButton;
    Button mVoiceInputButton;


    //消息标识位,当你发送消息的时候，你能
    //确定你发送的消息添加到列表的位置，但是
    //如果你发送的时候同时收到消息，这样就是导致有误差，所以需要这么一个标识位
    int mMessageFlag = 0;

    //聊天联系人
    Contact mContact;
    //自己
    User mMySelfInfo;

    private static List<Object> mData;

    EMConversation mConversation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_char);
        mContext = this;
        mContact = (Contact) getIntent().getSerializableExtra("contact");
        mMySelfInfo = AllenUtils.getSharedPreferencesObjData(mContext,"user_info","user");
        mCharWithUser = mContact.getName();
        mData = new ArrayList<>();
        AllenUtils.setActionBarColor(getWindow(), this, R.color.toolbar_color);
        initToolbar();
        initRecyclerView();
        initBottomInputView();
        //receiver message listener

        //初始化聊天信息
        initSessionRecord();
    }



    @Override
    protected void onResume() {
        super.onResume();
        //注册消息监听器
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        //指定会话未读出清零

        //如果获取存储的信息失败，则发送请求获取最新的用户信息
        if(mMySelfInfo==null){
        }

        //发送请求获取聊天记录

    }

    /**
     * 初始化聊天信息
     */
    private void initSessionRecord() {
        if(mContact.getName()!=null&&!mContact.getName().equals("")) {
            List<EMMessage> list = HttpUtils.getAllMessages(mContact.getName());
            if (list != null) {
                for (EMMessage msg : list) {
                    EMTextMessageBody body = (EMTextMessageBody) msg.getBody();
                    //将消息置为已读
                    HttpUtils.markMessageAsRead(mMySelfInfo.getName(),msg.getMsgId());
                    if (body instanceof EMTextMessageBody){
                        //属于文本消息
                        addTextItemForHistory(msg);
                    }
                }
                mCharAdapter.updateListDate(mData);
                mCharRecyclerView.scrollToPosition(mData.size() - 1);
            }
        }
    }

    /**
     * 一进聊天界面时，设置聊天记录。
     */
    private void addTextItemForHistory(EMMessage msg) {
        String content =((EMTextMessageBody) msg.getBody()).getMessage();
        String msgTime = AllenUtils.getDateFormat(msg.getMsgTime(),"yyyy-MM-dd HH:mm");
        mMessageFlag = mMessageFlag+1;
        System.out.println("caodaoxin msgTime = " + msgTime);
        System.out.println("caodaoxin content = " + content);
        System.out.println("caodaoxin  msg.to() = " +  msg.getTo());
        if(msg.getTo().equals(mMySelfInfo.getName())){
            //接收
            mData.add(new CharText(content,msgTime,MESSAGE_SEND_SUCCESS,CharText.CONTENT_TYPE_RECEIVER,
                    mContact.getHeaderImage(),mMessageFlag,true));
        }else{
            //发送
            mData.add(new CharText(content,msgTime,MESSAGE_SEND_SUCCESS,CharText.CONTENT_TYPE_SEND,
                    mContact.getHeaderImage(),mMessageFlag,true));
        }
    }

    /**
     * 初始化底部输入布局
     */
    private void initBottomInputView() {
        mEditSendText = (EditText) findViewById(R.id.char_keyboard_input_edit);
        mShowVoiceButton = (CircleImageView) findViewById(R.id.char_keyboard_input_voice);
        mAddExpressionButton = (CircleImageView) findViewById(R.id.char_bottom_keyboard_expression);
        mAddOtherButton = (CircleImageView) findViewById(R.id.char_button_input_add_other);
        mVoiceInputButton = (Button) findViewById(R.id.char_voice_input_button);
        mEditSendText.setOnEditorActionListener(this);

        mVoiceInputButton.setOnClickListener(this);
        mAddOtherButton.setOnClickListener(this);
        mShowVoiceButton.setOnClickListener(this);
        mAddExpressionButton.setOnClickListener(this);
    }
    private void initRecyclerView() {
        mCharRecyclerView = (RecyclerView) findViewById(R.id.char_recycler_view);
        mCharRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        mCharAdapter = new CharRecyclerAdapter(mContext,mData);
        mCharRecyclerView.setAdapter(mCharAdapter);
    }
    private void initToolbar() {
        TextView toolbarTitle = (TextView) findViewById(R.id.char_toolbar_name_title);
        if(mCharWithUser!=null){
            toolbarTitle.setText(mCharWithUser);
        }
        mGoBackButton = (TextView) findViewById(R.id.char_go_back);
        mGoBackButton.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.char_go_back:
                finish();
                break;
            case R.id.char_button_input_add_other:
                //暂时使用
                sendTextMessage();
                break;
            case R.id.char_keyboard_input_voice:
                //显示隐藏语音按钮
                mVoiceInputButton.setVisibility(mVoiceInputButton.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
                mEditSendText.setVisibility(mVoiceInputButton.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
                break;
        }
    }


    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()){
            case R.id.char_voice_input_button:
                //长按发送语音键
                sendVoiceMessage();
                break;
        }
        return false;
    }


    /**
     * 发送语音消息
     */
    private void sendVoiceMessage() {

    }
    /**
     * 发送文本消息
     */
    private void sendTextMessage() {
        if(mEditSendText.getText().toString().trim().equals("")){
            AllenUtils.showToast(mContext,getResources().getString(R.string.can_not_send_empty));
            return ;
        }

        //聊天列表添加数据
        mMessageFlag = mMessageFlag + 1;
        mData.add(new CharText(mEditSendText.getText().toString(), AllenUtils.getCurTime("yyyy-MM-dd HH:mm"), MESSAGE_SEND_PROGRESS, CharText.CONTENT_TYPE, mMySelfInfo.getHeader_image(), mMessageFlag,false));
        mCharAdapter.updateListDate(mData);
        mCharRecyclerView.scrollToPosition(mData.size() - 1);
        //发送聊天信息
        HttpUtils.sendTextMessage(mEditSendText.getText().toString(), mCharWithUser, HttpUtils.Chat, new EMCallBack() {
            @Override
            public void onSuccess() {
                //发送成功，发送请求，向服务器添加聊天记录
                updateMessageSendStatus(MESSAGE_SEND_SUCCESS);
            }

            @Override
            public void onError(int i, String s) {
                //发送失败，显示失败图标
                updateMessageSendStatus(MESSAGE_SEND_ERROR);
            }

            @Override
            public void onProgress(int i, String s) {
                //发送失败，显示失败图标
                updateMessageSendStatus(MESSAGE_SEND_PROGRESS);
            }
        }) ;

        //制空搜索框
        mEditSendText.setText("");
    }

    /**
     * @param view 被监听的对象
     * @param actionId  动作标识符,如果值等于EditorInfo.IME_NULL，则回车键被按下。
     * @param event    如果由输入键触发，这是事件；否则，这是空的(比如非输入键触发是空的)。
     * @return 返回你的动作
     */
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        System.out.println("onEditorAction event = "+ event.getAction());
        if(view.getText().toString().trim().equals("")){
            AllenUtils.showToast(mContext,getResources().getString(R.string.can_not_send_empty));
            return true;
        }
        //发送文本消息
        sendTextMessage();
        return true;
    }



    /**
     * 更新消息发送状态
     * @param flag 发送状态标识符：成功、发送中、失败
     */
    public void updateMessageSendStatus(final int flag){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (Object obj : mData) {
                    if (obj instanceof CharText) {
                        CharText ct = (CharText) obj;
                        if (ct.getFlag() == mMessageFlag) {
                            ct.setIsSendSuccess(flag);
                            int postion = mData.indexOf(obj);
                            mData.set(postion, ct);
                        }

                    }
                }
                //更新适配器
                mCharAdapter.updateListDate(mData);
            }
        });
    }

    /**
     * 更新消息未读状态
     * @param flag
     */
    public void updateMessageReadStatus(final boolean flag){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (Object obj : mData) {
                    if (obj instanceof CharText) {
                        CharText ct = (CharText) obj;
                        if (ct.getFlag() == mMessageFlag) {
                            ct.setRead(flag);
                            int position = mData.indexOf(obj);
                            mData.set(position, ct);
                        }

                    }
                }
                //更新适配器
                mCharAdapter.updateListDate(mData);
            }
        });
    }


    /**
     * 接收到文本消息
     */
    private void receiverTextMessage(final EMMessage msg) {
        HttpUtils.markMessageAsRead(mMySelfInfo.getName(),msg.getMsgId());
        //判断是否为单聊
        if (msg.getChatType()== EMMessage.ChatType.Chat){
            //接收到消息，添加聊天列表item，刷新列表
            //如果接收的用户是当前用户
            String fromUser = msg.getUserName();
            if(fromUser.equals(mContact.getName())){
                updateMessageReadStatus(true);
                String message = ((EMTextMessageBody) msg.getBody()).getMessage();
                mData.add(new CharText(message,AllenUtils.getCurTime("yyyy-MM-dd HH:mm"),MESSAGE_SEND_SUCCESS,CharText.CONTENT_TYPE_RECEIVER,mContact.getHeaderImage(),mMessageFlag,true));
            }
        }
        mCharAdapter.updateListDate(mData);
        mCharRecyclerView.scrollToPosition(mData.size() - 1);
    }


    //消息监听器
    EMMessageListener msgListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            for (EMMessage msg:messages){
                 switch (msg.getType()){
                     case TXT://文本
                         receiverTextMessage(msg);
                         break;
                     case VOICE://语音
                         break;
                     case VIDEO://视频
                         break;
                     case FILE://文件
                          break;
                     case LOCATION://定位
                         break;
                 }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            System.out.print("messages = " + messages.toString() );
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //receiver is read a receipt
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            // receipt a receipt
        }
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //The message was withdrawn.
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //message state change
        }
    };



    @Override
    protected void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }



    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

        }
    };

}
